package com.hong.concurrent.chapter17;

import java.util.Arrays;

/**
 * @Author csh
 * @Description 传送带
 * @Date 2018/7/11 21:16
 */
public class Channel {
    /**最大值*/
    private final  static int MAX_REQUEST = 100;
    /**存放工作队列*/
    private final Request[] requestQueue;
    /**队头*/
    private int head;
    /**队尾*/
    private int tail;
    /**总人数*/
    private int count;
    /**存放工人线程*/
    private final WorkerThread[] workerPool;

    public Channel(int workers){
        this.requestQueue = new Request[MAX_REQUEST];
        this.head = 0;
        this.tail= 0;
        this.count=0;
        this.workerPool = new WorkerThread[workers];
        this.init();
    }

    private void init() {
        for (int i =0;i<workerPool.length;i++){
            workerPool[i] = new WorkerThread("Worker-"+i,this);
        }
    }
    /**开关 开始工作*/
    public  void startWorkers(){
        Arrays.asList(workerPool).forEach(WorkerThread::start);
    }
    /**添加*/
    public synchronized void put(Request request){
        while (count>=requestQueue.length){
            try {
                this.wait();
            }catch (Exception e){

            }
        }
        this.requestQueue[tail] = request;
        this.tail = (tail+1)%requestQueue.length;
        this.count++;
        this.notifyAll();
    }

    /**
     * 取
     * @return
     */
    public synchronized Request take(){
        while (count<=0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Request request = this.requestQueue[head];
        this.head = (this.head+1)%this.requestQueue.length;
        this.count--;
        this.notifyAll();
        return request;
    }


}
